## ----12-transport-1, message=FALSE, results='hide'-----------------------
library(sf)
library(dplyr)
library(spDataLarge)
library(stplanr)      # geographic transport data package
library(tmap)         # visualization package (see Chapter 8)

## ----12-transport-2, echo=FALSE, eval=FALSE------------------------------
## # code that generated the input data - see also ?bristol_ways
## # source("https://github.com/Robinlovelace/geocompr/raw/master/code/12-transport-data-gen.R")
## # view input data
## summary(bristol_ways)
## summary(bristol_ttwa)
## summary(bristol_region)
## 
## region_all = rbind(bristol_region, bristol_ttwa)
## library(tmap)
## tmap_mode("view")
## qtm(bristol_ways, lines.col = "highway", lines.lwd = 3, lines.palette = c("green", "black", "red")) +
##   tm_scale_bar() +
##   tm_shape(region_all) +
##   tm_borders(lwd = c(5, 7), col = "darkblue")

## ----bristol, echo=FALSE, fig.cap="Bristol's transport network represented by colored lines for active (green), public (railways, black) and private motor (red) modes of travel. Blue border lines represent the inner city boundary and the larger Travel To Work Area (TTWA).", fig.scap="Bristol's transport network."----
knitr::include_graphics("https://user-images.githubusercontent.com/1825120/34452756-985267de-ed3e-11e7-9f59-fda1f3852253.png")

## ----12-transport-3, eval=FALSE, echo=FALSE------------------------------
## if(!require(readODS)) {
##   install.packages("readODS")
## }
## u = "https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/536823/local-area-walking-and-cycling-in-england-2015.zip"
## download.file(u, "local-area-walking-and-cycling-in-england-2015.zip")
## unzip("local-area-walking-and-cycling-in-england-2015.zip")
## View(readODS::read_ods("Table index.ods"))
## cw0103 = readODS::read_ods("cw0103.ods")
## View(cw0103)

## Another issue with small zones is related to anonymity rules.

## ----12-transport-5------------------------------------------------------
names(bristol_zones)

## ----12-transport-6------------------------------------------------------
nrow(bristol_od)
nrow(bristol_zones)

## ----12-transport-7------------------------------------------------------
zones_attr = bristol_od %>% 
  group_by(o) %>% 
  summarize_if(is.numeric, sum) %>% 
  dplyr::rename(geo_code = o)

## ----12-transport-8------------------------------------------------------
summary(zones_attr$geo_code %in% bristol_zones$geo_code)

## ----12-transport-9------------------------------------------------------
zones_joined = left_join(bristol_zones, zones_attr, by = "geo_code")
sum(zones_joined$all)
names(zones_joined)

## ----12-transport-10-----------------------------------------------------
zones_od = bristol_od %>% 
  group_by(d) %>% 
  summarize_if(is.numeric, sum) %>% 
  dplyr::select(geo_code = d, all_dest = all) %>% 
  inner_join(zones_joined, ., by = "geo_code")

## ----12-transport-11, eval=FALSE-----------------------------------------
## qtm(zones_od, c("all", "all_dest")) +
##   tm_layout(panel.labels = c("Origin", "Destination"))

## ----zones, echo=FALSE, fig.cap="Number of trips (commuters) living and working in the region. The left map shows zone of origin of commute trips; the right map shows zone of destination (generated by the script 12-zones.R).", message=FALSE, fig.scap="Number of trips (commuters) living and working in the region."----
source("https://github.com/Robinlovelace/geocompr/raw/master/code/12-zones.R", print.eval = TRUE)

## ----12-transport-12-----------------------------------------------------
od_top5 = bristol_od %>% 
  arrange(desc(all)) %>% 
  top_n(5, wt = all)

## ----od, echo=FALSE------------------------------------------------------
od_top5 %>% 
  knitr::kable(
    caption = paste("Sample of the origin-destination data stored in the data",
                    "frame object `bristol_od`. These represent the top 5 most", 
                    "common desire lines between zones in the study area."),
    short.caption = "Sample of the origin-destination data.",
    booktabs = TRUE)

## ----12-transport-13-----------------------------------------------------
bristol_od$Active = (bristol_od$bicycle + bristol_od$foot) /
  bristol_od$all * 100

## ----12-transport-14-----------------------------------------------------
od_intra = filter(bristol_od, o == d)
od_inter = filter(bristol_od, o != d)

## ----12-transport-15, warning=FALSE--------------------------------------
desire_lines = od2line(od_inter, zones_od)

## ----12-transport-16, eval=FALSE-----------------------------------------
## qtm(desire_lines, lines.lwd = "all")

## ----desire, echo=FALSE, warning=FALSE, message=FALSE, fig.cap="Desire lines representing trip patterns in Bristol, with width representing number of trips and color representing the percentage of trips made by active modes (walking and cycling). The four black lines represent the interzonal OD pairs in Table 7.1.", fig.asp=0.8, fig.scap="Desire lines representing trip patterns in Bristol."----
source("https://github.com/Robinlovelace/geocompr/raw/master/code/12-desire.R", print.eval = TRUE)

## ----12-transport-17, message=FALSE--------------------------------------
desire_lines$distance = as.numeric(st_length(desire_lines))
desire_carshort = dplyr::filter(desire_lines, car_driver > 300 & distance < 5000)

## ----12-transport-18, eval=FALSE-----------------------------------------
## route_carshort = line2route(desire_carshort, route_fun = route_osrm)

## ----12-transport-19-----------------------------------------------------
desire_carshort$geom_car = st_geometry(route_carshort)

## ----routes, warning=FALSE, fig.cap="Routes along which many (300+) short (<5km Euclidean distance) car journeys are made (red) overlaying desire lines representing the same trips (black) and zone centroids (dots).", echo=FALSE, eval=FALSE, fig.scap="Routes along which many car journeys are made."----
## # commented-out as it adds little to the chapter (RL)
## plot(st_geometry(desire_carshort))
## plot(desire_carshort$geom_car, col = "red", add = TRUE)
## plot(st_geometry(st_centroid(zones_od)), add = TRUE)

## ----12-transport-20-----------------------------------------------------
desire_rail = top_n(desire_lines, n = 3, wt = train)

## ----12-transport-21-----------------------------------------------------
ncol(desire_rail)
desire_rail = line_via(desire_rail, bristol_stations)
ncol(desire_rail)

## ----stations, echo=FALSE, message=FALSE, warning=FALSE, fig.cap="Station nodes (red dots) used as intermediary points that convert straight desire lines with high rail usage (black) into three legs: to the origin station (red) via public transport (gray) and to the destination (a very short blue line).", fig.scap="Station nodes."----
zone_cents = st_centroid(zones_od)
zone_cents_rail = zone_cents[desire_rail, ]
plot(desire_rail$geometry, expandBB = c(.1, .1, .1, .1))
plot(desire_rail$leg_orig, add = TRUE, col = "red", lwd = 3)
plot(desire_rail$leg_via, add = TRUE, col = "gray", lwd = 2)
plot(bristol_stations, add = TRUE, col = "red")
plot(desire_rail$leg_dest, add = TRUE, col = "blue", lwd = 5)
plot(zone_cents_rail, add = TRUE, col = "black")
# library(tmap)
# tmap_mode("plot")
# qtm(bristol_stations, basemaps = "https://{s}.tile.thunderforest.com/transport/{z}/{x}/{y}.png?apikey=feae177da543411c9efa64160305212d", dots.col = "red", symbols.size = 2) +
#   tm_shape(desire_rail) +
#   tm_lines(col = "black", lwd = 4) +
#   tm_shape(legs) +
#   tm_lines()

## ----12-transport-22-----------------------------------------------------
summary(bristol_ways)

## ----12-transport-23-----------------------------------------------------
ways_freeway = bristol_ways %>% filter(maxspeed == "70 mph") 
ways_sln = SpatialLinesNetwork(ways_freeway)
slotNames(ways_sln)
weightfield(ways_sln)
class(ways_sln@g)

## ----wayssln, fig.cap="Illustration of a small route network, with segment thickness proportional to its betweenness, generated using the igraph package and described in the text.", fig.asp=0.8, fig.scap="Illustration of a small route network."----
e = igraph::edge_betweenness(ways_sln@g)
plot(ways_sln@sl$geometry, lwd = e / 500)

## ----12-transport-24, eval=FALSE, echo=FALSE-----------------------------
## # not producing groups of routes so removing for now...
## m = igraph::clusters(ways_sln@g)
## igraph::V(ways_sln@g)$m = m$membership
## gdf = igraph::as_long_data_frame(ways_sln@g)

## ----12-transport-25, eval=FALSE-----------------------------------------
## route_rail = desire_rail %>%
##   st_set_geometry("leg_orig") %>%
##   line2route(route_fun = route_osrm) %>%
##   st_set_crs(4326)

## ----12-transport-26-----------------------------------------------------
route_cycleway = rbind(route_rail, route_carshort)
route_cycleway$all = c(desire_rail$all, desire_carshort$all)

## ----12-transport-27, eval=FALSE, echo=FALSE-----------------------------
## n_trips = route_cycleway$all / 100
## plot(route_cycleway["distance"], lwd = n_trips)

## ----12-transport-28, eval=FALSE-----------------------------------------
## qtm(route_cycleway, lines.lwd = "all")

## ----cycleways, echo=FALSE, message=FALSE, fig.cap="Potential routes along which to prioritise cycle infrastructure in Bristol, based on access key rail stations (red dots) and routes with many short car journeys (north of Bristol surrounding Stoke Bradley). Line thickness is proportional to number of trips.", fig.asp=0.8, fig.scap="Routes along which to prioritise cycle infrastructure."----
source("https://github.com/Robinlovelace/geocompr/raw/master/code/12-cycleways.R")
m_leaflet
# tmap_leaflet(m_leaflet) # not working
# online figure - backup
# u = "https://user-images.githubusercontent.com/1825120/39901156-a8ec9ef6-54be-11e8-94fb-0b5f6b48775e.png"

## ----12-transport-29, eval=FALSE, echo=FALSE-----------------------------
## sum(route_cycleway$distance)
## sum(st_length(route_cycleway))

## ----12-transport-30, echo=FALSE, eval=FALSE-----------------------------
## sum(route_cycleway$all) / sum(desire_lines$all) # around 2%
## d_intersect = desire_lines[route_cycleway, , op = st_crosses]
## sum(d_intersect$all) / sum(desire_lines$all) # around 2%

